package light.head.framework.utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.springframework.web.multipart.MultipartFile;

/**
 * @author janhang
 * @2010-12-15 下午03:30:24
 */
public class ImageUtils {
	
	/**
	 * 压缩图片
	 * @param 上传文件对象
	 * @param 最大宽度或高度
	 * @param 路径
	 */
	public boolean compression(MultipartFile mf, Integer wOh, String tPath) {
		BufferedImage sImg = null;
		try {
			sImg = ImageIO.read(mf.getInputStream());
		} catch (IOException e) {
			return false;
		}
		int nw = 0, nh = 0;
		
		if (null != wOh) {
			int sWidth = sImg.getWidth();
			int sHeight = sImg.getHeight();
			if (sWidth >= sHeight) {
				nw = wOh;
				nh = sHeight / (sWidth / nw);
			} else {
				nh = wOh;
				nw = sWidth / (sHeight / nh);
			}
		} else {
			nw = sImg.getWidth();
			nh = sImg.getHeight();
		}
		
		BufferedImage image = new BufferedImage(nw, nh, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = image.createGraphics();
		
		g.drawImage(sImg, 0, 0, nw, nh, null);
		g.dispose();
		
		try {
			FileUtils fu = new FileUtils();
			fu.createDir(tPath);
			File tFile = new File(tPath);
			ImageIO.write((BufferedImage) image, "jpg", tFile);
		} catch (IOException e) {
			return false;
		}
		
		return true;
	}
}
